package cn.js189.uqc.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 智慧BSS，静态数据映射关系类
 * 
 * @author Mid
 */
public class BSSHelper {
	
	private BSSHelper(){
		/*EMPTY*/
	}
	
	// 日志组件
	private static final Logger LOGGER = LoggerFactory.getLogger(BSSHelper.class);

	// 10,000,000,000
	private static final long BSS_TCP_CONT_TEN_THOUSAND = 10000L;

	// tcpCont交易流水中随机数的长度
	private static final int BSS_TCP_CONT_TRANS_ID_RANDOM_LENGTH = 4;

	// 时间格式yyyyMMddHHmmss
	private static final String BSS_TCP_CONT_DATE_FORMAT = "yyyyMMddHHmmss";

	/**
	 * 生成head信息
	 */
	public static JSONObject getRspInfo(String status, String msg) {
		long random = (long) (Math.random()* BSS_TCP_CONT_TEN_THOUSAND);
		StringBuilder sb = new StringBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat(BSS_TCP_CONT_DATE_FORMAT);
		String nowString = sdf.format(new Date());
		sb.append(nowString);
		String randomStr = String.valueOf(random);
		int zeroPaddingLen = BSS_TCP_CONT_TRANS_ID_RANDOM_LENGTH - randomStr.length();
		if (zeroPaddingLen > 0) {
			for (int i = 0; i < zeroPaddingLen; i++) {
				sb.append("0");
			}
		}
		sb.append(randomStr);

		JSONObject resObj = new JSONObject();
		resObj.put("responseId", sb.toString());
		resObj.put("status", status);
		resObj.put("msg", msg);
		resObj.put("responseTime", nowString);
		return resObj;
	}
	
	
	/**
	 * 生成错误和异常的body，head信息
	 */
	@SafeVarargs
	public static JSONObject getErrInfo(String status, String msg, Map<String,String> ... bodyMap) {
		long random = (long) (Math.random() * BSS_TCP_CONT_TEN_THOUSAND);
		StringBuilder sb = new StringBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat(BSS_TCP_CONT_DATE_FORMAT);
		String nowString = sdf.format(new Date());
		sb.append(nowString);
		String randomStr = String.valueOf(random);
		int zeroPaddingLen = BSS_TCP_CONT_TRANS_ID_RANDOM_LENGTH - randomStr.length();
		if (zeroPaddingLen > 0) {
			for (int i = 0; i < zeroPaddingLen; i++) {
				sb.append("0");
			}
		}
		sb.append(randomStr);
		
		JSONObject resObj = new JSONObject();
		JSONObject head = new JSONObject();
		JSONObject body = new JSONObject();
        if (bodyMap != null && bodyMap.length > 0) {
	        for (Entry<String, String> stringStringEntry : bodyMap[0].entrySet()) {
		        Entry<String, String> entry = stringStringEntry;
		        body.put(entry.getKey(), entry.getValue());
	        }
        }
		head.put("responseId", sb.toString());
		head.put("status", status);
		head.put("msg", msg);
		head.put("responseTime", nowString);
		resObj.put("head", head);
		resObj.put("body", body);
		return resObj;
	}


	/**
	 * 针对企信返回code为0,resultObject为null时,生成错误和异常的body，head信息
	 * @param status 状态码
	 * @param msg 提示信息
	 * @param bodyObj body节点内容
	 */
	public static JSONObject getErrInfoWithNullResObj(String status, String msg,JSONObject bodyObj) {
		long random = (long) (Math.random() * BSS_TCP_CONT_TEN_THOUSAND);
		StringBuilder sb = new StringBuilder();
		SimpleDateFormat sdf = new SimpleDateFormat(BSS_TCP_CONT_DATE_FORMAT);
		String nowString = sdf.format(new Date());
		sb.append(nowString);
		String randomStr = String.valueOf(random);
		int zeroPaddingLen = BSS_TCP_CONT_TRANS_ID_RANDOM_LENGTH - randomStr.length();
		if (zeroPaddingLen > 0) {
			for (int i = 0; i < zeroPaddingLen; i++) {
				sb.append("0");
			}
		}
		sb.append(randomStr);
		JSONObject resObj = new JSONObject();
		JSONObject head = new JSONObject();
		head.put("responseId", sb.toString());
		head.put("status", status);
		head.put("msg", msg);
		head.put("responseTime", nowString);
		resObj.put("head", head);
		resObj.put("body", bodyObj);
		return resObj;
	}

	/**
	 * 老入参accNbrType转3.0 prodId
	 */
	public static String accNbrTypeToProdId(String accNbrType){
		Map<String, String>map=new HashMap<String, String>();
		//key为老的入参类型;value为新类型
		//固话
		map.put("1", "100000002");
		//宽带
		map.put("2", "100000009");
		//手机
		map.put("9", "100000379");
		map.put("379", "100000379");
		String prodId=map.get(accNbrType);
		if(StringUtils.isBlank(prodId)){
			LOGGER.debug("accNbrTypeToProdId return is null!");
		}
		return prodId;
	}
	
	/**
	 * 老入参accNbrType转3.0 prodId
	 */
	public static String prodspecIdToProdId(String prodSpecId){
		Map<String, String>map=new HashMap<String, String>();
		//key为老的入参类型;value为新类型
		map.put("9", "100000009");
		String prodId=map.get(prodSpecId);
		if(StringUtils.isBlank(prodId)){
			LOGGER.debug("prodSpecIdToProdId return is null!");
		}
		return prodId;
	}
	
	
	/**
	 * 3.0 prodId转 老入参accNbrType
	 *
	 */
	public static String prodIdToAccNbrType(String prodId){
		Map<String, String>map=new HashMap<String, String>();
		//key为老的入参类型;value为新类型
		//固话
		map.put("100000002", "1");
		//宽带
		map.put("100000009", "2");
		//手机
		map.put("100000379", "379");
		//itv
		map.put("100000881","881");
		String accNbrType=map.get(prodId);
		if(StringUtils.isBlank(accNbrType)){
			LOGGER.debug("prodId return is null!");
		}
		return accNbrType;
	}
	
	/**
	 * 新老证件类型转换
	 * 0返回老类型,1返回新类型；
	 * 0新转老,1老转新
	 */
	public static String getIndentType(int tag,String indentType){
		if(0!=tag &&  1!=tag){
			LOGGER.debug("tag is err");
			return "0";
		}
		String returnType="-1";
		//输出的证件类型下标
		int resultIndex=tag==0?1:0;
		// 新99 对应 原来老的 多个
		if (0 == tag && "99".equals(indentType)) {
			returnType="21";
		}
		StringBuilder sql = new StringBuilder();
		//二维数组的0为新的证件类型;1为老的证件类型
		sql.append("39,3;");
		sql.append("99,4;");
		sql.append("99,5;");
		sql.append("99,12;");
		sql.append("99,13;");
		sql.append("99,18;");
		sql.append("99,19;");
		sql.append("99,22;");
		sql.append("2,26;");
		sql.append("99,46;");
		sql.append("99,48;");
		sql.append("1,1;");
		sql.append("2,2;");
		sql.append("3,9;");
		sql.append("4,49;");
		sql.append("5,23;");
		sql.append("6,52;");
		sql.append("7,24;");
		sql.append("9,6;");
		sql.append("10,8;");
		sql.append("11,7;");
		sql.append("12,25;");
		sql.append("13,17;");
		sql.append("14,47;");
		sql.append("15,11;");
		sql.append("17,27;");
		sql.append("18,28;");
		sql.append("22,29;");
		sql.append("23,30;");
		sql.append("24,31;");
		sql.append("25,10;");
		sql.append("26,32;");
		sql.append("27,33;");
		sql.append("28,34;");
		sql.append("29,35;");
		sql.append("30,36;");
		sql.append("31,37;");
		sql.append("32,38;");
		sql.append("33,39;");
		sql.append("34,40;");
		sql.append("35,41;");
		sql.append("36,42;");
		sql.append("37,43;");
		sql.append("38,44;");
		sql.append("39,-1;");
		sql.append("40,-1;");
		sql.append("41,51;");
		sql.append("42,50;");
		sql.append("43,45;");
		sql.append("45,-1;");
		sql.append("46,-1;");
		sql.append("47,-1;");
		sql.append("48,-1;");
		sql.append("99,21");
		String[]indenTypeOneArr=sql.toString().split(";");
		for (String s : indenTypeOneArr) {
			String[] indenTypeTwoArr = s.split(",");
			if (indentType.equals(indenTypeTwoArr[tag])) {
				returnType = indenTypeTwoArr[resultIndex];
			}
		}
		//处理证件类型为其他时
		//99为新类型其他；21为老类型其他
		if (0 == tag && "-1".equals(returnType)) {
			returnType = "21";
		}
		if (1 == tag && "-1".equals(returnType)) {
			returnType = "99";
		}
		
		if(0==tag){
			LOGGER.debug("new[{}] to old is[{}}].....................",indentType,returnType);
		}else{
			LOGGER.debug("old[{}] to new is[{}].....................",indentType,returnType);
		}
		
		return returnType;
		
	}
	
	/**
	 * Description: 字符串转Document<br>
	 * @author 刘添<br>
	 * @return <br>
	 */
    public static Document convertDocFromStr(String xml) {
        try {
            return DocumentHelper.parseText(xml);
        } catch (DocumentException e) {
            return null;
        }
    }

    /**
     * 
     * Description: 获取xml某个节点的值 <br>
     * @author 刘添<br>
     * @return <br>
     */
    public static String getNodeByXml(String xml, String node) {
        Document doc = convertDocFromStr(xml);
        if (doc == null) {
            return null;
        } else {
            Node typeNode = doc.selectSingleNode(".//*[local-name()='" + node
                    + "']");
            if (typeNode == null) {
                return null;
            } else {
                return typeNode.getStringValue();
            }
        }
    }
	
    /**
     * Description: 日期转换 <br>
     * @author chenxiang<br>
     * @return <br>
     */
	public static String dateChange(String date) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat formats = new SimpleDateFormat("yyyyMMdd");
		String newDate = "";
		try {
			Date dateTime = format.parse(date);
			newDate = formats.format(dateTime);
			LOGGER.info(newDate);
		} catch (ParseException e) {
		    LOGGER.debug("日期转换错误");
		}
		return newDate;
	}
	
	/**
	 * Description: 根据字符获取,字符串中该字符,后面所有的字符串<br>
	 */
	public static String subStringByLastChar(String str) {
		String restr = "";
		//用于将产品服务规格改为老版的规格
		try{
		   String a = str.substring(1);
		   int b = Integer.parseInt(a);
		   restr =b+"";
		}catch(Exception e){
		    LOGGER.debug("将产品服务规格改为老版的规格错误");
		}
		return restr;
	}
	
	public static String fillStringByTwoChar(String str,String charStr1,String charStr2){
	    String restr ="";
	    int length = str.length();
	    try{
		    StringBuilder strBuilder = new StringBuilder(str);
		    for(int i = length; i<8; i++){
	            strBuilder.insert(0, charStr1);
	        }
		    str = strBuilder.toString();
		    restr=charStr2+str;
	    }catch(Exception e){
	        LOGGER.debug("错误");
	    }
	    return restr;
	}
	
	/**
	 * 
	 * Description: <br> 
	 *  
	 * @author yangyang<br>
	 * 2018年8月1日
	 * @return String<br>
	 */
	public static String prodSpecIdToProdKindId(String prodSpecId){
	    String prodKindId = "";
	    if("2".equals(prodSpecId)){//固话
	        prodKindId ="1";
	    }else if("9".equals(prodSpecId)){//宽带
	        prodKindId ="3";
	    }else{//由于没有小灵通了，所以不可能出现prodKindId=2的情况，其余都为4
	        prodKindId="4";
	    }
	    return prodKindId;
	}
	
	/**
	 * 预付费和后付费
	 * Description: <br> 
	 *  
	 * @author yangyang<br>
	 * 2018年8月10日
	 * @return String<br>
	 */
	public static String newPayMethodToOld(String newPayMethod){
	    String oldpayMethod = "";
	    if("2100".equals(newPayMethod)){
	        oldpayMethod = "1";
	    }else if("1200".equals(newPayMethod)){
	        oldpayMethod ="2";
	    }else{
	        oldpayMethod = newPayMethod;//无法区分
	    }
	    return oldpayMethod;
	}
}
